<template>
  <page-content center>
    <div style="overflow-x: auto;">
      <space class="my-1 header-actions">
        <a-button @click="onExpand">展开</a-button>
        <a-button @click="onCollapse">收起</a-button>
        <loading-action :action="storeApiDocument">生成Api文档</loading-action>
        <a-button @click="onExport">导出Postman格式</a-button>
        <lz-popconfirm :confirm="truncateApiDocument()">
          <a-button class="error-color">清空</a-button>
        </lz-popconfirm>
      </space>

      <nested-draggable
        ref="models"
        :expand-keys="defaultExpanded"
        class="system-models"
        :list="apiDocuments"
        handle=".drag"
      >
        <template #default="{ data }">
          <div class="item-wrap">
              <span class="ml-1" v-if="data.showdoc_url">
                <a :href="data.showdoc_url" target="_blank">
                  {{ data.name }}
                </a>
              </span>
              <span class="ml-1" v-else>
                {{ data.name }}
              </span>
          </div>
          <div class="flex-spacer"/>
          <space style="min-width: 120px;">
            <doc-preview
              v-if="data.content"
              :title="data.name"
              :label="`Postman格式预览`"
              :content="`<pre>`+JSON.stringify(data.content, null, 4)+`</pre>`"
            />
          </space>
          <space style="min-width: 480px;">
            <span class="ml-1" v-if="data.created_at">
              创建时间：{{ data.created_at }}
            </span>
            <span class="ml-1" v-if="data.updated_at">
              更新时间：{{ data.updated_at }}
            </span>
          </space>
        </template>
      </nested-draggable>
    </div>
  </page-content>
</template>

<script>
import {
  getApiDocuments,
  getFormatApiDocument,
  storeApiDocument,
  truncateApiDocument,
} from '@/api/api-documents'
import LzPopconfirm from '@c/LzPopconfirm'
import {
  hasChildren
} from '@/libs/utils'
import NestedDraggable from '@c/NestedDraggable'
import Space from '@c/Space'
import PageContent from '@c/PageContent'
import LoadingAction from '@c/LoadingAction'
import DocPreview from '@c/DocPreview'

export default {
  name: 'Index',
  scroll: true,
  components: {
    Space,
    NestedDraggable,
    LzPopconfirm,
    PageContent,
    LoadingAction,
    DocPreview
  },
  data() {
    return {
      apiDocuments: [],
      apiDocumentsBak: '',
      // 默认展开第二级模型
      defaultExpanded: [],
    }
  },
  created() {
    this.getApiDocuments()
  },
  activated() {
    // 缓存的页面，由于不会执行 created 方法，所以滚动行为，放在该钩子里
    this.$scrollResolve()
  },
  methods: {
    async getApiDocuments() {
      const { data } = await getApiDocuments()
      this.apiDocuments = data
      this.apiDocumentsBak = JSON.stringify(this.apiDocuments)
      this.defaultExpanded = this.apiDocuments.filter(i => hasChildren(i)).map(i => i.id)

      this.$scrollResolve()
    },
    hasChildren,
    onExpand() {
      this.$refs.models.expandAll()
    },
    onCollapse() {
      this.$refs.models.collapseAll()
    },
    /**
     * 获取模型结构，仅包含 id 和 children 字段
     * @param apiDocuments
     * @returns {Array}
     */
    getApiDocumentstruct(apiDocuments = this.apiDocuments) {
      const struct = []
      apiDocuments.forEach((i) => {
        struct.push({
          id: i.id,
          children: hasChildren(i)
            ? this.getApiDocumentstruct(i.children)
            : undefined,
        })
      })
      return struct
    },
    async onExport() {
      const { data } = await getFormatApiDocument()
      const blob = new Blob(
        [JSON.stringify(data, null, 2)],
        { type: 'application/json' },
      )
      
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = data.info.name
      link.click()

      window.URL.revokeObjectURL(link.href)
    },
    truncateApiDocument() {
      return async () => {
        await truncateApiDocument()
        this.apiDocuments = []
      }
    },
    async storeApiDocument() {
      await storeApiDocument()
      this.getApiDocuments()
    },
  },
}
</script>

<style scoped lang="less">
@import "~@/styles/vars";

.system-models {
  width: 1100px;

  .id {
    width: 40px;
    display: inline-block;
    text-align: center;
    font-weight: bolder;
  }

  .drag {
    cursor: move;
  }

  .path {
    color: @primary-color;
  }

  .item-wrap {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

.header-actions {
  width: 100%;
  overflow-x: auto;
}
</style>
